/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 * sschaffe
 *
 * File Info:
 * User: sschaffe
 * Date: 2011/01/13
 * Time: 13:22
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.social.webservices.tagging;

import kiwi.core.api.config.ConfigurationService;
import kiwi.core.api.content.ContentItemService;
import kiwi.core.api.facading.FacadingService;
import kiwi.core.api.triplestore.ResourceService;
import kiwi.core.model.rdf.KiWiResource;
import kiwi.core.model.rdf.KiWiTriple;
import kiwi.core.model.user.KiWiUser;
import kiwi.core.qualifiers.transaction.Transactional;
import kiwi.core.qualifiers.user.CurrentUser;
import kiwi.core.services.io.RdfJsonSerializer;
import kiwi.social.api.tagging.TaggingService;
import kiwi.social.model.tagging.Tagging;
import org.slf4j.Logger;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

/**
 * Add file description here!
 * <p/>
 * User: sschaffe
 */
@ApplicationScoped
@Path("/social/tagging")
@Produces({"application/json"})
@Transactional
public class TaggingWebService {

    @Inject
    private Logger log;

    @Inject
    private ConfigurationService configurationService;

    @Inject
    private TaggingService taggingService;


    @Inject
    private ResourceService resourceService;

    @Inject
    private ContentItemService contentItemService;

    @Inject
    private FacadingService facadingService;

    @Inject
    private RdfJsonSerializer rdfJsonSerializer;


    @Inject @CurrentUser
    private KiWiUser currentUser;


    /**
     * Create a new tagging for the item identified by taggedItemUri. Either taggingItemUri or tagLabel must be given.
     *
     * @param taggedItemUri
     * @param taggingItemUri
     * @param tagLabel
     */
    @Path("/create")
    @POST
    @Produces("text/plain")
    public Response createTagging(@QueryParam("taggedItemUri") String taggedItemUri,
                              @QueryParam("taggingItemUri") String taggingItemUri,
                              @QueryParam("tagLabel") String tagLabel) throws URISyntaxException {




        // ensure correctness of syntax
        try {
            URI ti1_uri = new URI(taggedItemUri);
            if(taggingItemUri != null) {
                URI ti2_uri = new URI(taggingItemUri);
            }
        } catch(URISyntaxException ex) {
            return Response.status(Response.Status.BAD_REQUEST).entity("the passed URIs have invalid syntax ("+ex.getMessage()+")").build();
        }

        KiWiResource taggedItem = resourceService.getUriResource(taggedItemUri);

        if(taggedItem != null) {
            if(taggingItemUri != null) {
                KiWiResource taggingResource = resourceService.createUriResource(taggingItemUri);

                Tagging tagging = taggingService.createTagging(tagLabel,taggedItem,taggingResource,currentUser);


                log.info("created tagging of resource {} -> {}",taggedItem,taggingResource);

                return Response.ok(tagging.getDelegate().toString()).build();

            } else if(tagLabel != null && !"".equals(tagLabel.trim())) {

                tagLabel = tagLabel.trim();

                Tagging tagging = taggingService.createTagging(taggedItem, tagLabel, currentUser);

                log.info("created tagging of resource {} -> label {}",taggedItem,tagLabel);

                return Response.ok(tagging.getDelegate().toString()).build();
             } else {

                return Response.status(Response.Status.BAD_REQUEST).entity("either taggedItemUri or tagLabel must be given.").build();
            }

        } else {

            return Response.status(Response.Status.NOT_FOUND).entity("could not find resource with URI "+taggedItemUri).build();
        }

    }


    /**
     * List all taggings of the resource identified by the URI passed as parameter "taggedItemUri". The parameter is
     * required.
     *
     * The output is a JSON object representing the RDF/JSON of the taggings.
     *
     * @param taggedItemUri
     * @return
     * @throws URISyntaxException
     */
    @Path("/list")
    @GET
    @Produces("application/json")
    public Response listTaggings(@QueryParam("taggedItemUri") String taggedItemUri) throws URISyntaxException {
        if(taggedItemUri != null) {
            // check syntax
            URI t_uri = new URI(taggedItemUri);

            KiWiResource resource = resourceService.getUriResource(taggedItemUri);

            if(resource != null) {

                List<Tagging> taggings = taggingService.getTaggingsByItem(resource);

                List<KiWiTriple> result = new LinkedList<KiWiTriple>();
                for(Tagging tagging : taggings) {
                    result.addAll(resourceService.listOutgoing(tagging.getDelegate()));
                }

                log.debug("result list contains {} elements",result.size());

                return Response.ok(rdfJsonSerializer.serializeTriples(result)).build();
            } else {
                return Response.status(Response.Status.NOT_FOUND).build();
            }
        } else {
            return Response.status(Response.Status.BAD_REQUEST).entity("the parameter taggedItemUri is required and cannot be omitted").build();
        }


    }



    @Path("/{uuid:.*}")
    @DELETE
    @Produces("text/plain")
    public Response removeTagging(@PathParam("uuid") String uuid) {
        KiWiResource r = resourceService.getUriResource(configurationService.getBaseUri()+"social/tagging/"+uuid);

        if(r != null) {
            taggingService.removeTagging(r);

            return Response.ok().build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("tagging with given URI does not exist").build();
        }
    }
}
